package jpa4azure.impl;

import static jpa4azure.type.TypeWrapperFactory.$;

import java.util.Date;

import javax.persistence.PersistenceException;

import jpa4azure.type.FieldContext;
import jpa4azure.type.Key;
import jpa4azure.type.TypeWrapper;

import com.windowsazure.samples.HttpStatusCode;
import com.windowsazure.samples.Property;
import com.windowsazure.samples.PropertyCollection;
import com.windowsazure.samples.table.AzureTableEntity;
import com.windowsazure.samples.table.AzureTableManager;

public class PersistOperation {

	//TableStorageClient client;
	AzureTableManager client;
	
	public PersistOperation(AzureTableManager client) {
		this.client = client;
	}

	public void save(Object entity) throws Exception {
		TypeWrapper type =  $(entity);
		Key key = type.id(entity);
		Date now = new Date();
		PropertyCollection props = new PropertyCollection(key.getPartition(), key.getRow(), now);
		for (FieldContext f : type.getFields(entity))
			f.getCloudTableColumn(props);
	    Property<?> typeProp = Property.newProperty("jpa4azureBeanType", type.getWrappedType().getName());
		props.add(typeProp);
		AzureTableEntity response =  client.insertEntity("", now, "jpa4azure", type.getTableName(), props);
		if (response.getHttpStatusCode() != HttpStatusCode.Created)
			throw new PersistenceException(response.getErrorCode());
		
	}
}
